<?php
namespace app\common\model;

use think\facade\Request;
use think\helper\Str;

abstract class Model extends \think\Model
{
    /**
     * 搜索选项
     * @var array
     */
    protected $searchOptions = [];

    /**
     * @var string 排序字段名（外部输入）
     */
    public string $orderInputKey = 'order';

    /**
     * @var bool|array 排序：array=允许排序的字段，true=不限制排序字段，false=不允许自动排序
     */
    public bool|array $orderAllow = false;

    public function __construct(array $data = [])
    {
        parent::__construct($data);

        $reflection = new \ReflectionClass($this);

        // 自动添加获取器
        foreach ($reflection->getConstants() as $constantName => $constantValue) {
            if (!strpos($constantName, '_datalist')) continue;
            $fieldOrigin = substr($constantName, 0, -9);
            $field = $fieldOrigin . '_text';
            if (method_exists($this, 'get' . Str::studly($field) . 'Attr')) continue;
            $this->withAttr($field, function($value, $data) use ($constantName, $fieldOrigin) {
                $list = constant(static::class . '::' . $constantName);
                return $list[$data[$fieldOrigin]];
            });
        }
    }

    /**
     * 获取搜索配置
     * @return array
     */
    public function getSearchOptions(): array
    {
        return $this->searchOptions;
    }
}